package service

import (
	sqlc "bgs/db/sqlc"
	"bgs/service/model"
	"bgs/util"
	"bgs/wxp/mina"
	"context"
	"fmt"
)

// GenLottery1Distribution 生成抽奖1的奖项分布
func GenLottery1PrizeDistribution(ctx context.Context, prizeRates []uint32, cardinality uint32) (distributions []model.PrizeDistribution, err error) {
	upper := int(cardinality)
	rng := make([]uint32, cardinality)
	for i := 0; i < upper; i++ {
		rng[i] = uint32(i + 1)
	}

	for idx, rate := range prizeRates {
		rateUpper := int(rate)
		var wins []uint32
		for i := 0; i < rateUpper; i++ {
			ridx := util.RandomInt(0, int32(len(rng)-1))
			rVal := rng[ridx]
			wins = append(wins, rVal)
			rng = append(rng[:ridx], rng[ridx+1:]...)
		}

		distributions = append(distributions, model.PrizeDistribution{
			Available: true,            // 生成时候一定是StockAvailable
			Prize:          uint32(idx + 1), // sort 从1开始递增完美符合奖项
			Wins:           wins,
		})
	}
	return
}

type UserCheckIn1 struct {
	UserOpenID             string
	ContinuousCheckInCount uint32
	ContinuousMaxCount     uint32 // 连签天数
}

type GenRemindCheckIn1NotifyMessageParam struct {
	ActivityID int64
	ActivityName  string
	BrandID int64
	BrandName     string
	UserCheckIn1s []*UserCheckIn1
}

// GenRemindCheckIn1NotifyMessage (主动,生成微信小程序消息=>签到提醒)
func (s *ActivityServiceImp) GenRemindCheckIn1NotifyMessage(ctx context.Context, q *sqlc.Queries, p GenRemindCheckIn1NotifyMessageParam) (rows []*mina.SendNotifyParam, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	brandID := p.BrandID
	name := fmt.Sprintf("%sX%s", p.ActivityName, p.BrandName)
	page := fmt.Sprintf("package-signin/pages/detail/index?brandId=%d", brandID)
	templateID := s.wechatVars.Tp1956 // "zUdNfurFZcB9JcbZnb_wa2Ux2__-CZqRiG2IyoTHjN4"
	tip := "温馨提示：连签7天有礼"

	for _, userCheckIn1 := range p.UserCheckIn1s {
		rows = append(rows, &mina.SendNotifyParam{
			UserOpenID: userCheckIn1.UserOpenID,
			Page:       page,
			TemplateID: templateID,
			MinaState:  s.wechatVars.MinaState,
			Content: map[string]map[string]interface{}{
				"thing1":  {"value": name},
				"number5": {"value": userCheckIn1.ContinuousCheckInCount},
				"thing7":  {"value": tip},
			},
		})
	}

	slog.Infof("生成微信小程序消息=>签到提醒 ok")

	return
}
